package com.mxpio.erp.equipment.job;

import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepTask;
import com.mxpio.erp.common.equipment.service.EquipmentUpkeepTaskService;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Classname TaskReleaseJob
 * @Description 任务自动下达
 */
@Slf4j
@Component
public class UpkeepTaskReleaseJob implements Job {

    @Autowired
    private EquipmentUpkeepTaskService tpmUpkeepTaskService;

    /**
     * 自动下达保养任务（每一分钟）
     */
    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        /**
         * 查询任务中需要下达的工单
         * 1.待下达的
         * 2.需要自动下达的
         * 3.下达时间在当前时间之后的
         */
        Criteria c = Criteria.create().addCriterion("orderStatus", Operator.EQ, EquipmentEnums.UpkeepStatus.START.getCode());
        c.addCriterion("isAutoRelease", Operator.EQ, 1);
        c.addCriterion("planReleaseTime", Operator.LE, new Date());
        c.addCriterion("pmisHold", Operator.EQ,EquipmentEnums.PmisHode.PRODUCTIONSCHEDULED.getCode());

        List<EquipmentUpkeepTask> list = tpmUpkeepTaskService.list(EquipmentUpkeepTask.class,c);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (EquipmentUpkeepTask tpmUpkeepTask : list) {
            tpmUpkeepTaskService.release(tpmUpkeepTask.getBizNo());
        }

    }
}
